//
//  TJSectionLabel.m
//  FontTest
//
//  Created by mac on 2024/8/25.
//

#import "TJSectionView.h"


@interface TJSectionModel()

@property (nonatomic, assign) BOOL ableEdit;


@end
 
@implementation TJSectionModel

- (NSString *)description {
    return [NSString stringWithFormat:@"text = %@, ableEdit = %d", _text, _ableEdit];
}

@end
 
@implementation TJSectionLabel


@end

@interface TJSectionView()

@property (nonatomic, strong) NSArray *ranges;
@property (nonatomic, strong) NSArray <TJSectionLabel *>*lables;
@property (nonatomic, assign) NSInteger totalW;


@end


@implementation TJSectionView

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        
        self.totalW = 0;
        
    }
    return self;
}

- (void)setIndexs:(NSArray *)indexs {
    _indexs = indexs;
    
    
    NSArray *rangeTexts = nil;
    if (indexs.count > 0) {
        
        NSArray *array = [self.class groupConsecutiveNumbers:indexs];
        NSMutableArray *ranges = [NSMutableArray array];
        
        [array enumerateObjectsUsingBlock:^(NSArray *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            NSRange range = NSMakeRange([obj.firstObject intValue], obj.count);
            if (self.text.length >= range.location + range.length) {
                [ranges addObject:[NSValue valueWithRange:range]];
            }
        }];
        self.ranges = ranges.copy;
        
        rangeTexts = [self.class extractAndSortSegmentsWithString:self.text ranges:self.ranges];
    } else {
        rangeTexts = @[self.text];
        self.ranges = @[[NSValue valueWithRange:NSMakeRange(0, self.text.length)]];
    }
    
    NSMutableArray *labels = [NSMutableArray array];
    [rangeTexts enumerateObjectsUsingBlock:^(NSString *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        TJSectionLabel *textLabel = [[TJSectionLabel alloc] init];
        textLabel.numberOfLines = 0;
//        textLabel.lineBreakMode = NSLineBreakByClipping;
        [self addSubview:textLabel];
        textLabel.text = obj;
        [labels addObject:textLabel];
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapLabel:)];
        textLabel.userInteractionEnabled = YES;
        [textLabel addGestureRecognizer:tap];
        
        TJSectionModel *model = [[TJSectionModel alloc] init];
        model.text = obj;
        textLabel.model = model;
    }];
    
    
    [self.ranges enumerateObjectsUsingBlock:^(NSValue   * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
       
        NSString *rangeString = [self.text substringWithRange:obj.rangeValue];
 
        for (TJSectionLabel *label in labels) {
            if ([label.model.text isEqualToString:rangeString]) {
                label.model.ableEdit = YES;
                break;
            }
        }
    }];
    
    self.lables = labels.copy;
 
    NSLog(@"rangeTexts = %@", rangeTexts);
}

- (void)setIsSelect:(BOOL)isSelect {
    _isSelect = isSelect;
    
    for (TJSectionLabel *label in self.lables) {
        if (label.model.ableEdit) {
            label.layer.borderColor = UIColorMake(0x2978F0).CGColor;
            if (isSelect) {
                label.layer.borderWidth = 1;
            } else {
                label.layer.borderWidth = 0;
            }
        }
    }
 

}

- (void)tapLabel:(UITapGestureRecognizer *)tap {
    
    TJSectionLabel *label = (TJSectionLabel *)tap.view;
    if (!label.model.ableEdit) {
        return;
    }
    
    NSLog(@"model = %@", label.model);
    if ([self.delegate respondsToSelector:@selector(sectionView:tapLabel:)]) {
        [self.delegate sectionView:self tapLabel:label];
    }
}

- (NSString *)getCurrentText {
    NSMutableString *string = [NSMutableString string];
    for (TJSectionLabel *label in self.lables) {
        [string appendString:label.model.text];
//        [string appendString:@"\n"];
    }
    return string;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    
 
    self.totalW = 0;
    
    for (int i = 0; i < self.lables.count; i++) {
        
        CGFloat labelW = 0;

        TJSectionLabel * _Nonnull obj = self.lables[i];
        obj.text = obj.model.text;
        [obj sizeToFit];
        
        //如果是总的200, 最大是250, 文字是60, 那么最多就是显示50
        if (self.totalW + obj.bounds.size.width > self.maxW) {
            labelW = self.maxW - self.totalW;
        } else {
            labelW = obj.bounds.size.width;
        }
    
        if (i == 0) {
            obj.frame = CGRectMake(0, 0, labelW, self.bounds.size.height);
        } else {
            obj.frame = CGRectMake(CGRectGetMaxX(self.lables[i - 1].frame), 0, labelW, self.bounds.size.height);
        }
        self.totalW = self.totalW + obj.bounds.size.width;
    }

    NSLog(@"totalW = %ld", self.totalW);
}

- (void)reloadData {
    [self layoutIfNeeded];
    [self setNeedsLayout];
}

- (void)setAttributedText:(NSAttributedString *)attributedText {
    _attributedText = attributedText;
    
    for (TJSectionLabel *label in self.lables) {
        label.attributedText = attributedText;
        NSLog(@"model = %@", label.model);
    }
}

+ (NSArray<NSArray<NSNumber *> *> *)groupConsecutiveNumbers:(NSArray<NSNumber *> *)array {
    if (array.count == 0) {
        return @[];
    }
    
    NSMutableArray<NSArray<NSNumber *> *> *result = [NSMutableArray array];
    NSMutableArray<NSNumber *> *currentGroup = [NSMutableArray array];
    
    // Iterate through the array
    for (NSInteger i = 0; i < array.count; i++) {
        // Add the current number to the current group
        [currentGroup addObject:array[i]];
        
        // Check if it's the last element or if the next element is not consecutive
        if (i == array.count - 1 || [array[i + 1] integerValue] != [array[i] integerValue] + 1) {
            [result addObject:[currentGroup copy]];
            [currentGroup removeAllObjects];
        }
    }
    
    return [result copy];
}

 
+ (NSArray<NSString *> *)extractAndSortSegmentsWithString:(NSString *)string ranges:(NSArray<NSValue *> *)ranges {
    NSUInteger length = string.length;
    
    BOOL *marked = calloc(length, sizeof(BOOL));
    NSMutableArray<NSString *> *segments = [NSMutableArray array];
    
    // Mark the ranges as split
    for (NSValue *rangeValue in ranges) {
        NSRange range = [rangeValue rangeValue];
        for (NSUInteger i = range.location; i < NSMaxRange(range) && i < length; i++) {
            marked[i] = YES;
        }
    }
    
    // Extract the split segments
    NSUInteger start = 0;
    while (start < length) {
        // Find the start of the next unmarked segment
        while (start < length && marked[start]) {
            start++;
        }
        
        if (start >= length) {
            break;
        }
        
        NSUInteger end = start;
        // Find the end of the current unmarked segment
        while (end < length && !marked[end]) {
            end++;
        }
        
        // Extract the substring for the current range
        if (start < end) {
            NSString *substring = [string substringWithRange:NSMakeRange(start, end - start)];
            [segments addObject:substring];
        }
        
        start = end;
    }
    
    // Extract the segments specified by the ranges
    for (NSValue *rangeValue in ranges) {
        NSRange range = [rangeValue rangeValue];
        if (range.location < length) {
            NSString *substring = [string substringWithRange:NSMakeRange(range.location, MIN(range.length, length - range.location))];
            [segments addObject:substring];
        }
    }
    
    // Sort the segments based on their original position in the string
    [segments sortUsingComparator:^NSComparisonResult(NSString *segment1, NSString *segment2) {
        NSRange range1 = [string rangeOfString:segment1];
        NSRange range2 = [string rangeOfString:segment2];
        return [@(range1.location) compare:@(range2.location)];
    }];
    
    free(marked);
    return [segments copy];
}

 

@end
